//
//  SShellRequest.m
//  TestForRequest
//
//  Created by admin on 2021/3/4.
//

#import "SShellRequest.h"
#import "ShellAPIResponse.h"

@interface SShellRequest ()
{
    // 缓存所有的block
    NSString * _kRequestUrl;
    id _kArgument;
    YTKRequestMethod _kMethod;
    NSDictionary * _kheaderFields;
    YTKRequestQueryStringSerializationStyle _kqueryStringSerializationStyle;
    YTKRequestSerializerType _krequestSerializerType;
}

@end

@implementation SShellRequest

- (NSString *)requestUrl{
    return _kRequestUrl ?: @"";
}
- (YTKRequestQueryStringSerializationStyle)requestQueryStringSerializationStyle {
    return _kqueryStringSerializationStyle ?: YTKRequestQueryStringDefaultStyle;
}
- (NSDictionary<NSString *,NSString *> *)requestHeaderFieldValueDictionary {
    return _kheaderFields ?: nil;
}
- (YTKRequestMethod)requestMethod {
    return _kMethod ?: YTKRequestMethodGET;
}
///  Additional request argument.
- (nullable id)requestArgument{
    return _kArgument ?: nil;
}
- (YTKRequestSerializerType)requestSerializerType {
    return _krequestSerializerType ?: YTKRequestSerializerTypeHTTP;
}


- (SShellStartBlock)startBlock {
    __weak typeof(self) weakSelf = self;
    return ^SShellRequest * _Nullable{
        [weakSelf startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
//            MMSPCLog(@"success in base :%@",request.requestUrl);
//            [iConsole log:@"%@ success in base :%@",[NSDate date],request.requestUrl];
//            [MBManager hideAlert];
            YTKResponseSerializerType responseType = request.responseSerializerType;
            switch (responseType) {
                case YTKResponseSerializerTypeJSON:
                {
                    if (![NSJSONSerialization isValidJSONObject:request.responseObject]) {
                        ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                        response.returnCode = @"-1";
                        response.returnMessage = NSLocalizedStringFromTable(@"abc_data_format_error", @"constant", nil);
                        response.request = request;
                        
                        weakSelf.failureResponseBlock(response);
                        return ;
                    }else{
                        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableContainers error:nil];
                        NSString* returnCode = json[@"retCode"];
                        NSString* returnMsg = json[@"retMsg"];
                        NSString* returnData = json[@"data"];
//                        if(returnCode.integerValue == 1 && inBlack == NO){
//                            if(![request.requestUrl containsString:@"queryocrmorg"]){
//                              [Utility showToast:returnMsg];
//                            }
//                        }
                        ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                        response.returnCode = returnCode;
                        response.returnMessage = returnMsg;
                        response.returnData = returnData;
                        response.request = request;
                        weakSelf.successResponseBlock(response);
                    }
                }
                    break;
                case YTKResponseSerializerTypeHTTP:
                {
                    ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                    response.request = request;
                    
                    weakSelf.successResponseBlock(response);
                }
                    break;
                default:
                {
                    ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                    response.returnCode = @"-1";
                    response.returnMessage = NSLocalizedStringFromTable(@"abc_data_format_error", @"constant", nil);
                    response.request = request;
                    
                    weakSelf.failureResponseBlock(response);
                }
                    break;
            }
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
//            MMSPCLog(@"failed in base :%@",request.requestUrl);
//            [iConsole log:@"%@failed in base :%@",[NSDate date],request.requestUrl];
//            [MBManager hideAlert];
            NSInteger statusCode = request.responseStatusCode;
            if (statusCode == 401 && request && request.responseData) {
                NSDictionary* json = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableContainers error:nil];
                NSString* returnCode = json[@"retCode"];
                if (returnCode && [returnCode integerValue] == 2) {
//                    [weakSelf returnCode_2_Operation];
                    
                    ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                    response.returnCode = returnCode;
                    response.request = request;
                    weakSelf.failureResponseBlock(response);
                    return ;
                }
            }else{
                
                ShellAPIResponse* response = [[ShellAPIResponse alloc] init];
                response.returnCode = @"-1";
                response.returnMessage = NSLocalizedStringFromTable(@"abc_network_error", @"constant", nil);
                response.returnData = nil;
                response.request = request;
                
                if(request.error.code == -1001){//超时
//                    [Utility showToast:[NSString stringWithFormat:@"%@%@", weakSelf.requestUrl,NSLocalizedStringFromTable(@"abc_time_out", @"constant", nil)]];
                    weakSelf.failureResponseBlock(response);
                    return;
                }
                //NSURLErrorCode 网络错误码
                NSString* alertMessage = [NSString stringWithFormat:@"%@ 错误码:%ld,状态码:%ld", NSLocalizedStringFromTable(@"abc_network_error", @"constant", nil),(long)request.error.code,(long)request.response.statusCode];
//                [iConsole log:@"LLLLLL fail error:%@,code%ld%@",request.error,request.error.code,request.error.description];
                
//                [Utility showToast:alertMessage];
                weakSelf.failureResponseBlock(response);
                
            }
        }];
//        [weakSelf start];
        return weakSelf;
    };
}


- (SShellRequest * _Nullable (^)(NSString * _Nonnull))requestUrlBlock {
    __weak typeof(self) weakSelf = self;
    return ^SShellRequest * _Nullable(NSString * _Nonnull url) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->_kRequestUrl = url;
        return weakSelf;
    };
}
- (SShellRequest * _Nullable (^)(id _Nonnull))requestArgumentBlock {
    __weak typeof(self) weakSelf = self;
    return ^SShellRequest * _Nullable(id _Nonnull argument) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->_kArgument = argument;
        return weakSelf;
    };
}
- (SShellRequest * _Nullable (^)(YTKRequestMethod))requestMethodBlock {
    __weak typeof(self) weakSelf = self;

    return ^SShellRequest * _Nullable(YTKRequestMethod method) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->_kMethod = method;
        return weakSelf;
    };
}


- (SShellRequest * _Nullable (^)(YTKRequestQueryStringSerializationStyle))shellSerializationStyleBlock {
    __weak typeof(self) weakSelf = self;
    
    return ^SShellRequest * _Nullable (YTKRequestQueryStringSerializationStyle style) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->_kqueryStringSerializationStyle = style;
        return weakSelf;
    };
}
- (SShellRequest * _Nullable (^)(NSDictionary * _Nullable))shellRequestHeaderFieldBlock {
    __weak typeof(self) weakSelf = self;
    
    return ^SShellRequest * _Nullable (NSDictionary * _Nullable headerFields) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->_kheaderFields = headerFields;
        return weakSelf;
    };
}
-(SShellRequest * _Nullable (^)(ABCAPIResponseBlock))shellSuccessblock{
    __weak typeof(self) weakSelf = self;

    return ^SShellRequest * _Nullable (ABCAPIResponseBlock aBlock) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.successResponseBlock = aBlock;
        return weakSelf;
    };
}
-(SShellRequest * _Nullable (^)(ABCAPIResponseBlock))shellFailureblock {
    __weak typeof(self) weakSelf = self;

    return ^SShellRequest * _Nullable (ABCAPIResponseBlock aBlock) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.failureResponseBlock = aBlock;
        return weakSelf;
    };
}
- (SShellRequest * _Nullable (^)(YTKRequestSerializerType))shellRequestSerializerTypBlock{
    __weak typeof(self) weakSelf = self;

    return ^SShellRequest * _Nullable (YTKRequestSerializerType type) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf->_krequestSerializerType = type;
        return weakSelf;
    };
}

-(void)dealloc {
    NSLog(@"%s",__FUNCTION__);
}
@end
